/*******************用户信息验证js*******************
 */
// loginName  登录名  英文+数字
function isLoginName(loginName) {
    var pattern = /^[a-zA-Z][a-zA-Z0-9]|[\\u2E80-\\u9FFF]*$/;
    return pattern.test(loginName);
}
// password  密码
function checkPassword(password) {
    var pattern = /^[a-z0-9]{6,16}$/;
    return pattern.test(password);
}
// age;  年龄
function isAge(emage) {
    var pattern = /^(?:[1-9]?\d|100)$/;
    return pattern.test(emage);
}
// Tel  电话号码  验证手机号 匹配国内电话号码(0511-4405222 或 021-87888822) /\d{3}-\d{8}|\d{4}-\d{7}/
function isTel(phone) {
    var pattern1 = /^1[34578]\d{9}$/;
    var pattern2 = /\d{3}-\d{8}|\d{4}-\d{7}/;
    if (pattern1.test(phone) || pattern2.test(phone)) {
        return true;
    }
    return false;
}
//邮箱验证^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$    /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/
function isEmail(strEmail) {
    if (strEmail.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
        return true;
    else
        return false;
}
//编号验证
function checkNumber(Number) {
    var pattern = /^[a-z0-9]{6,12}$/;
    return pattern.test(Number);
}
// 上传头像，并回显
$(".addEmPhoto").bind('change', function () {
    var fordate = new FormData();  // 得到一个FormData对象：
    var fils = $(".addEmPhoto").get(0).files[0];  // 得到file对象
    fordate.append('pic', fils);  // 用append方法添加键值对
    var result = uploadfile('addEmPhoto'); // 上传头像并返回结果
    if (result.code == 0) {
        $(".imagePhoto").attr({'src': result.data}); // 把图片回显
        $(".strPhoto").val(result.data); // 将路径存入不显示的文本框中
        $('.tipuserPhoto').html("√").css("color", "green");
    } else {
        alert("上传头像失败，请重新上传！");
    }
});
// 点击头像
function showPhotoFun(id) {
    $.ajax({
        type: "GET",
        url: "/userInfoController/findOneUser?id=" + id,
        dataType: "json",
        success: function (data) {
            $(".imagePhoto").attr({'src': data.userp.userPhoto});
        },
        error: function () {
            alert("发送请求失败！");
        }
    });
}
///用户是否重复验证方法体
function isRepeat(url, value) {
    var result = false;
    $.ajax({
        type: "GET",
        url: url + value,
        dataType: "json",
        async: false,   //同步
        success: function (data) {
            if (data.userp != null) {
                result = true;
            } else {
                result = false;
            }
        },
        error: function () {
            alert(" 请求效验失败！");
        }
    });
    return result;
}

//vipId
function isEquality2(url, value) {

    var result = false;
    $.ajax({
        type: "GET",
        url: url + value,
        dataType: "json",
        async: false,   //同步
        success: function (data) {
            if (data.vipinf != null){
                if (data.vipinf.vipNo == value) {
                    result = true;
                } else {
                    $('.vipNo').val(data.vipinf.vipId);
                }
            }

        },
        error: function () {
            alert(" vip请求效验失败！");
        }
    });
    return result;

}

//请求匹配  babyId
function isEquality(url, value) {

    var result = false;
    $.ajax({
        type: "GET",
        url: url + value,
        dataType: "json",
        async: false,   //同步
        success: function (data) {
            console.log(data);
            if (data.bb != null && (data.bb.babyId != null && data.bb.babyId != undefined)){
                $('.fileNo').val(data.bb.babyId);
            }else {
                result = true;
            }
        },
        error: function () {
            alert(" baby请求效验失败！");
        }
    });
    return result;

}


var result = false;


//判断用户名
$('.userName').on("blur", function () {

    if (!$.trim($('.userName').val())) {
        $('.tiploginName').html(" * 不能为空!").css("color", "red");
    } else {
        if (isLoginName($.trim($('.userName').val())) == false) {
            $('.tiploginName').html(" * 用户名不合法！").css("color", "red");
        } else {
            result = "true";
            $('.tiploginName').html("√").css("color", "green");
        }
    }
});

//判断密码:
$('.password').on("blur", function () {

    if (!$.trim($('.password').val())) {
        $('.tippassword').html("*密码不能为空！").css("color", "red");
    } else {
        if (checkPassword($.trim($('.password').val())) == false) {
            $('.tippassword').html("*密码格式错误！").css("color", "red");
        } else {
            // 验证通过
            result = 'true';
            $('.tippassword').html("√").css("color", "green");
        }
    }
});

//确认密码:
$('.password2').on("blur", function () {

    if (!$.trim($('.password2').val())) {

        $('.tippassword2').html("*确认密码不能为空！").css("color", "red");
    } else if ($.trim($('.password2').val()) != $.trim($('.password').val())) {

        $('.tippassword2').html("*确认密码错误！").css("color", "red");
    } else {
        // 验证通过
        result = "true";
        $('.tippassword2').html("√").css("color", "green");

    }
});

// 判断年龄
$('.userAge').on("blur", function () {
    // 判断年龄
    if ($.trim($('.userAge').val()).length == 0) {
        $('.tipemage').html("*年龄不能为空！").css("color", "red");
    } else {
        if (isAge($.trim($('.userAge').val())) == false) {
            $('.tipemage').html("*年龄不合法！").css("color", "red");
        } else {
            // 验证通过
            result = "true";
            $('.tipemage').html("√").css("color", "green");
        }
    }
});

//判断电话
$('.userTel').on("blur", function () {

    if ($.trim($('.userTel').val()).length == 0) {
        $('.tipemTel').html("*电话不能为空！").css("color", "red");
    } else {
        if (isTel($.trim($('.userTel').val())) == false) {
            $('.tipemTel').html("*电话不合法！").css("color", "red");
        } else {
            // 验证通过
            result = "true";
            $('.tipemTel').html("√").css("color", "green");
        }
    }
});

//判断邮箱
$('.userMail').on("blur", function () {
    if ($.trim($('.userMail').val()).length == 0) {
        $('.tipUserMail').html("*邮箱不能为空！").css("color", "red");
    } else {
        if (isEmail($.trim($('.userMail').val())) == false) {
            $('.tipUserMail').html("*邮箱不合法！").css("color", "red");
        } else {
            // 验证通过
            result = "true";
            $('.tipUserMail').html("√").css("color", "green");
        }
    }
});

//判断会员卡号
$('.vipId').on("blur", function () {
    if (!$.trim($('.vipId').val())) {
        $('.tipvipId').html(" * 不能为空！").css("color", "red");
    } else {
        if (checkNumber($.trim($('.vipId').val())) == false) {
            $('.tipvipId').html(" * 会员卡号不合法！").css("color", "red");
        } else {

            result = "true";
            $('.tipvipId').html("√").css("color", "green");

        }
    }
});

$('.babyId').on("blur", function () {
    //宝宝编号是否为空:
    if ($.trim($('.babyId').val()).length == 0) {
        $('.tipbabyId').html(" * 不能为空！").css("color", "red");
    } else {
        if (checkNumber($.trim($('.babyId').val())) == false) {
            $('.tipbabyId').html(" * 宝宝编号不合法！").css("color", "red");
        } else {

            result = "true";
            $('.tipbabyId').html("√").css("color", "green");

        }

    }
});

//判断全部通过
function isUserInfo() {
    result = false;
    //头像
    if (!$('.strPhoto').val()) {
        $('.tipuserPhoto').html(" * 不能为空!").css("color", "red");
    } else {
        //用户名
        if (!$.trim($('.userName').val())) {
            $('.tiploginName').html(" * 不能为空!").css("color", "red");
        } else {
            if (isLoginName($.trim($('.userName').val())) == false) {
                $('.tiploginName').html(" * 用户名不合法！").css("color", "red");
            } else {
                //密码
                if (!$.trim($('.password').val())) {
                    $('.tippassword').html("*密码不能为空！").css("color", "red");
                } else {
                    if (checkPassword($.trim($('.password').val())) == false) {
                        $('.tippassword').html("*密码格式错误！").css("color", "red");
                    } else {
                        //确认密码
                        if (!$.trim($('.password2').val())) {

                            $('.tippassword2').html("*确认密码不能为空！").css("color", "red");
                        } else if ($.trim($('.password2').val()) != $.trim($('.password').val())) {

                            $('.tippassword2').html("*确认密码错误！").css("color", "red");
                        } else {
                            //年龄
                            if ($.trim($('.userAge').val()).length == 0) {
                                $('.tipemage').html("*年龄不能为空！").css("color", "red");
                            } else {
                                if (isAge($.trim($('.userAge').val())) == false) {
                                    $('.tipemage').html("*年龄不合法！").css("color", "red");
                                } else {
                                    //电话
                                    if ($.trim($('.userTel').val()).length == 0) {
                                        $('.tipemTel').html("*电话不能为空！").css("color", "red");
                                    } else {
                                        if (isTel($.trim($('.userTel').val())) == false) {
                                            $('.tipemTel').html("*电话不合法！").css("color", "red");
                                        } else {
                                            //邮箱
                                            if ($.trim($('.userMail').val()).length == 0) {
                                                $('.tipUserMail').html("*邮箱不能为空！").css("color", "red");
                                            } else {
                                                if (isEmail($.trim($('.userMail').val())) == false) {
                                                    $('.tipUserMail').html("*邮箱不合法！").css("color", "red");
                                                } else {
                                                    // 会员卡号
                                                    if (!$.trim($('.vipId').val())) {
                                                        $('.tipvipId').html(" * 不能为空！").css("color", "red");
                                                    } else {
                                                        if (checkNumber($.trim($('.vipId').val())) == false) {
                                                            $('.tipvipId').html(" * 会员卡号不合法！").css("color", "red");
                                                        } else {
                                                            //宝宝编号
                                                            if ($.trim($('.babyId').val()).length == 0) {
                                                                $('.tipbabyId').html(" * 不能为空！").css("color", "red");
                                                            } else {
                                                                if (checkNumber($.trim($('.babyId').val())) == false) {
                                                                    $('.tipbabyId').html(" * 宝宝编号不合法！").css("color", "red");
                                                                } else {
                                                                    $('.tipbabyId').html("√").css("color", "green");
                                                                    var viptype =  $("#vipId").val();
                                                                    if (viptype == null  || viptype == undefined || viptype =='') {
                                                                        $('.typevip').html(" * 会员卡类型不合法！").css("color", "red");
                                                                    }else{
                                                                        $('.typevip').html("√").css("color", "green");
                                                                        result = true;
                                                                    }

                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return result;
}

// 添加用户验证函数
function addUserFormValidate() {
    result = false;
    //用户名验证请求
    var url = "/userInfoController/findOneUser?userName=";
    var value = $.trim($(".userName").val());

    if (isRepeat(url, value)) {
        $('.tiploginName').html(" * 用户名已存在！").css("color", "red");
    } else {
        //电话重复验证
        var url = "/userInfoController/findOneUser?userTel=";
        var value = $.trim($(".userTel").val());
        if(isRepeat(url, value)){
            $('.tipemTel').html(" * 电话号码已存在！").css("color", "red");
        }else{
            // //会员卡号验证请求
            var url = "/vipInfoController/findOneVipInfo?vipNo=";
            var value = $.trim($('.vipId').val());
            if (isEquality2(url, value)) {
                $('.tipvipId').html(" * 会员卡已存在！").css("color", "red");
            } else {
                //宝宝编号验证请求
                var url = "/babyInfoController/findOneBabyInfo?fileNo=";
                var value = $.trim($(".babyId").val());
                if (isEquality(url, value)) {
                    $('.tipbabyId').html(" * 宝宝编号不存在").css("color", "red");
                } else {
                    result = true;
                    $('.tipbabyId').html("√").css("color", "green");
                }
            }
        }
    }
    return result;
}

//验证请求匹配
function isUserInfo2() {
    if (addUserFormValidate())
        return true;
    else
        return false;
}

//添加用户
$('#submitAddUserBtn').on('click', function () {

        if (confirm("您确定添加当前用户的数据？")) {

            if (isUserInfo2() && isUserInfo()) {
                $.ajax({
                    type: "POST",
                    url: "/userInfoController/addUserInfo",
                    dataType: "json",
                    data: $('#addUserForm').serialize(),
                    async: false,
                    success: function (data) {
                        if (data.result == "true") {
                            alert("添加失败！");
                        } else {
                        if(addVipInfo()){
                      //      alert("添加失败!");
                            }else{
                            updateId();
                           }
                      }
                    },
                    error: function () {
                        alert("发送请求失败！");
                    }
                });
            } else {
                alert("* 用户未添加!!!请检查红色提示!");
            }
        } else {
            alert("用户未添加!!!");
        }
    }
);

// 获得用户信息
function editEmpFun(id) {
    $("#submitAddUserBtn").hide();
    $.ajax({
        type: "GET",
        url: "/userInfoController/findOneUser?id=" + id,
        dataType: "json",
        async: false,
        success: function (data) {
            /****************查询出来显示在查看页面标签中*****************/
            // 头像
            $(".imagePhoto").attr("src", data.userp.userPhoto);
            $(".strPhoto").val(data.userp.userPhoto); // 将路径存入不显示的文本框中
            // 唯一标识（用于保存修改的时候的id）
            $(".Id").val(data.userp.id);
            // 用户名
            $(".userName").val(data.userp.userName);
            // 密码
            $(".password").val(data.userp.password);
            $(".password2").val(data.userp.password);
            // 性别
            if (data.userp.userSex == 1) {
                $(".userSex:eq(0)").attr("checked", "checked");
            } else {
                $(".userSex:eq(1)").attr("checked", "checked");
            }
            // 会员、学员
            if (data.userp.reserve1 == 0) {
                $(".reserve1:eq(0)").attr("checked", "checked");
            } else {
                $(".reserve1:eq(1)").attr("checked", "checked");
            }
            // 年龄
            $(".userAge").val(data.userp.userAge);
            // 用户婚姻状况
            if (data.userp.marriage == 1) {
                $(".marriage1:eq(0)").attr("checked", "checked");
            } else {
                if (data.userp.marriage == 2) {
                    $(".marriage:eq(1)").prop("checked", "checked");
                } else {
                    $(".marriage:eq(2)").prop("checked", "checked");
                }
            }
            // 电话
            $(".userTel").val(data.userp.userTel);
            // 邮箱
            $(".userMail").val(data.userp.userMail);
            // 住址
            $(".userAddress").val(data.userp.userAddress);
            //vip等级
            var vipid = data.userp.vipId;
            // 宝宝id
           var babyid = data.userp.babyId
            if (vipid != null && vipid != undefined && vipid != ''){

               var opselected = $("#vipId").find("option[value = '"+vipid+"']")[0];
               var optext =$(opselected)[0].innerHTML;
               var opvalue =$(opselected)[0].value;
               document.getElementById("vipId").removeChild(opselected);
               var str = '<option value='+opvalue+' selected >'+optext+'</option>';
                $("#vipId").append(str);

            }
           if (babyid != null && babyid != undefined && babyid != '') {
               $('.fileNo').val(data.userp.babyId);
               $.ajax({
                   type: "GET",
                   url: "/userInfoController/findOneBabyInfo?babyId=" + babyid,
                   dataType: "json",
                   // async: false,   //同步
                   success: function (data) {
                       // alert(data.bb.fileNo);
                       if (data.bb.babyId == babyId ) {
                           $('.babyId').val(data.bb.fileNo);
                           $('.fileNo').val(data.bb.babyId);
                       }
                   },
                   error: function () {
                       alert("babyid发送请求失败！");
                   }
               });
           }

            var Id = $('.Id').val();
            var babyId = $('.fileNo').val();
            //与宝宝关系
            var relation = data.userp.reserve2;
            if (relation != null && relation != undefined && relation != ''){
                $(".reserve2").val(relation);
            }

            //VI卡号
            $.ajax({
                type: "GET",
                url: "/userInfoController/findOneVipInfo?userId=" + Id ,
            //    dataType: "json",
                async: false,   //同步
                success: function (data) {
                    console.log(data);
                    // alert(data.vipinf.vipNo);
                    if (data.vipinf != null && data.vipinf != undefined) {
                        if (data.vipinf.userId == Id) {
                            $('.vipId').val(data.vipinf.vipNo);
                            $('.vipId').attr("disabled","disabled");
                            $('.vipNo').val(data.vipinf.vipId);
                            $('.userId').val(data.vipinf.userId);
                        }
                    }
                },
                error: function () {
                    alert("vip发送请求失败1！");
                }
            });

        },
    });
}

// 删除用户信息
function delEmpFun(id) {
    $("#delEmpConfirm").modal({
        onConfirm: function () {
            $.ajax({
                type: "GET",
                url: "/userInfoController/deleteUserInfo?id=" + id,
                dataType: "json",
                success: function (data) {
                    if (data.result == "success") {
                        alert("删除成功！");
                        window.location.reload();
                    } else {
                        alert("删除失败！");
                    }
                },
                error: function () {
                    alert("发送请求失败！");
                }
            });
        }
    });
}

//验证是否重复验证
function isUserName() {
    var url="/userInfoController/findOneUser?userName=";
    var value = $.trim($(".userName").val());
    var Id = $.trim($(".Id").val());
    var result = false;
    $.ajax({
        type: "GET",
        url: url + value,
        dataType: "json",
        async: false,   //同步
        success: function (data) {
            if (data.userp == null) {
                result = true;
            }else if(data.userp.id == Id){
                result = true;
            }
        },
        error: function () {
            alert("用户是否已存在验证失败！");
        }
    });
    return result;
}

//vipid
function isvipId() {
   var url = "/vipInfoController/findOneVipInfo?vipNo=";
   var value = $.trim($('.vipId').val());
    var Id = $.trim($(".userId").val());
    var result = false;
    $.ajax({
        type: "GET",
        url: url + value,
        dataType: "json",
        async: false,   //同步
        success: function (data) {
            if (data.vipinf == null) {
                result = true;
            }else if(data.vipinf.userId == Id){
                result = true;
            }
        },
        error: function () {
            alert("vipId否已存在验证失败！");
        }
    });
    return result;
}

//babyId
function isbabyId() {
    var url = "/babyInfoController/findOneBabyInfo?fileNo=";
    var value = $.trim($(".babyId").val());
    var Id = $.trim($(".fileNo").val());
    var result = false;
    $.ajax({
        type: "GET",
        url: url + value,
        dataType: "json",
        async: false,   //同步
        success: function (data) {
            if (data.bb == null) {
                result = true;
            }else if(data.bb.babyId == Id){
                result = true;
            }
        },
        error: function () {
            alert("babyId否已存在验证失败！");
        }
    });
    return result;
}

//验证请求是否成功!
function isUserInfo3() {
       var  result = true;
    if(isUserName()){
    }else{
        result =false;
        $('.tiploginName').html(" * 用户名重复！").css("color", "red");
    }

    //会员卡号验证请求
    if (isvipId()) {
        $('.tipvipId').html("√").css("color", "green");
    } else {
        result = false;
        $('.tipvipId').html(" * 会员卡已存在！").css("color", "red");
    }
    //宝宝编号验证请求
    var url = "/babyInfoController/findOneBabyInfo?fileNo=";
    var value = $.trim($(".babyId").val());
    if (isEquality(url, value)) {
        result = false;
        $('.tipbabyId').html(" * 宝宝编号不存在").css("color", "red");
    } else {
        $('.tipbabyId').html("√").css("color", "green");
    }

    //通过
    if(result){
        return true;
    }else{
        return false;
    }

}

//更新用户信息
function updateUserFun() {

    if (confirm("您确定更新当前用户的数据？")) {
        // 前端验证
        if (isUserInfo3() && isUserInfo()) {

            $.ajax({
                type: "POST",
                url: "/userInfoController/updateUserInfo",
                dataType: "json",
                data: $('#addUserForm').serialize(),
                async: false,
                success: function (data) {
                    console.log(data);
                    if (data.result == "success") {
                    //    updateVipInfo();
                        alert("更新成功！");
                        window.location.reload();
                    } else {
                        alert("用户更新失败！");
                    }
                },
                error: function () {
                    alert("发送请求失败！");
                }
            });

        }else{
            alert(" * 信息有误，请检查红色提示!");
        }
    }else{
        alert("用户未更新!");
    }
}

// 隐藏修改按钮
function hideBtn() {
    $("#updateUserBtn").hide();
}

// 给按钮设置（取消，关闭）点击刷新网页
$('.clearForm').on('click', function () {
    window.location.reload();
});

//向vipInfo里面添加数据
function addVipInfo() {
    $.ajax({
        type: "POST",
        // url: "/vipInfoController/addVipInfo",
        url: "",
        dataType: "json",
        data: $('#addUserForm').serialize(),
        async: false,
        success: function (data) {
            if(data.result == "success"){
            } else {
                alert("添加失败");
            }
        },
        error: function () {
       //     alert("vip发送请求失败2！");
        }
    });
}
//更新VIPInfo表的数据
function updateVipInfo(){
    $.ajax({
        type: "POST",
        url: "/vipInfoController/updateVipInfo",
        dataType: "json",
        data: $('#addUserForm').serialize(),
        success: function (data) {
            if (data.result == "success") {
                alert("更新成功！");
                window.location.reload();
            } else {
                alert("更新失败！");
            }
        },
        error: function () {
         //   alert("发送请求失败！");
        }
    });
}

//添加用户辅助
function updateId() {
    var vipNo = $.trim($('.vipId').val());
    $.ajax({//1
        type: "POST",
        url: "/vipInfoController/findOneVipInfo?vipNo="+vipNo,
        dataType: "json",
        async: false,
        success: function (data) {
            if (data.vipinf != null) {
                $('.vipNo').val(data.vipinf.vipId);
                var userName = $.trim($('.userName').val());

                $.ajax({//2
                    type: "POST",
                    url: "/userInfoController/findOneUser?userName="+userName,
                    dataType: "json",
                    async: false,
                    success: function (data) {
                            // 唯一标识（用于保存修改的时候的id）
                            $(".Id").val(data.userp.id);

                            $.ajax({//3 end
                                type: "POST",
                                url: "/userInfoController/updateUserInfo",
                                dataType: "json",
                                data: $('#addUserForm').serialize(),
                                success: function (data) {
                                    if (data.result == "success") {
                                        alert("添加成功！");
                                        window.location.reload();
                                    } else {
                                        alert("添加失败！");
                                    }
                                },
                                error: function () {
                                    alert("发送请求失败！");
                                }
                            });
                    },
                    error: function () {
                        alert("发送请求失败！");
                    }
                });

            } else {
                alert("添加失败");
            }
        },
        error: function () {
        //    alert("vip发送请求失败3！");
        }
    });
}

// 模糊查询
$("#searchBtn").on("click", function () {
    var type = $("#searchType").val();
    var content = $("#searchContent").val();
    // alert(type + ":" + content);
    if (content === null || content === undefined || content === '' || content.length === 0) {
        alert("请输入查询条件！");
        return false;
    } else {
        window.location.href="/userInfoController/searchUserInfo?type="+type+"&content="+content;
        $.ajax({
            type: 'POST',
            data: {"type": type, "content": content},
            url: "/userInfoController/searchUserInfo",
            cache: false,
            success: function (data) {
                $("table").remove();
                $(".content_pageinfor_ul2").remove();
                $(".content_pageinfor_ul").remove();
                var $data = $(data); // 将整个文档转化为jquery对象
                var content = $data.find("table");
                var content_pageinfor=$data.find(".content_pageinfor_ul2");
                $(".content_pageinfor2").append(content_pageinfor);
                $(".tableDiv").append(content);
                $("#searchContent").val(content);
            },
            error: function () {
                alert("请求失败！");
            }
        });
    }
});

//激活用户
function changeActive(uid) {
    var fdata =new FormData();
    fdata.append("id",uid);
    fdata.append("state",1);
    $.ajax({
        type: "POST",
        url: "/userInfoController/updateUserInfo?id="+uid+"&state=1",
        dataType: "json",
        async: false,
        success: function (data) {
            if (data.result == "success") {
                window.location.reload();
            } else {
                alert("用户更新失败！");
            }
        },
        error: function () {
            alert("网络出问题了！");
        }
    });
}